package com.learn.training.multithread.chapter12.demo1;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Demo {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("start main thread...");

        // 传入Runnable实例并立刻运行
        Thread vt1 = Thread.startVirtualThread(() ->{
            System.out.println("start virtual thread run now...");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("end virtual thread run now...");
        });
        vt1.join();




        // 创建虚拟线程但不自动运行，而是手动调用start()开始运行：
//        Thread vt2 = Thread.ofVirtual().unstarted(() -> {
//            System.out.println("start virtual thread not run...");
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            System.out.println("end virtual thread not run...");
//        });
//        //运行
//        vt2.start();

        // 通过虚拟线程的ThreadFactory创建虚拟线程，然后手动调用start()开始运行：
//        ThreadFactory tf = Thread.ofVirtual().factory();
//        Thread vt3 = tf.newThread(() -> {
//            System.out.println("start virtual thread by factory...");
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            System.out.println("end virtual thread by factory...");
//        });
//        vt3.start();


        // 创建调度器
//        ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
//
//        // 创建大量虚拟线程并调度
//        ThreadFactory tf1 = Thread.ofVirtual().factory();
//        for(int i = 0; i < 100000; i++) {
//            Thread t = tf1.newThread(() -> {
//                System.out.println("start virtual thread by executor..." + "     " + Thread.currentThread().getName());
//            });
//            executor.submit(t);

            // 也可以直接传入Runnable 或 Callable实例：
//            executor.submit(() ->{
//                System.out.println("start virtual thread...");
//                Thread.sleep(1000);
//                System.out.println("end virtual thread...");
//                return true;
//            });
//        }



        Thread.sleep(50000);



    }

}
